package workqueues;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;
import utils.RabbitMQUtil;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

public class Worker {

    public static final String TASK_QUEUE_NAME = "task_queue";

    public static void main(String[] args) throws IOException, TimeoutException {
        
        Channel channel = RabbitMQUtil.getChannel();
        channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
        
        channel.basicQos(1);

        DeliverCallback deliverCallback = (consumerTag, message) -> {
            String msg = new String(message.getBody(), StandardCharsets.UTF_8);
            System.out.println(" [x] Received '" + msg + ";");
            try {
                doWork(msg);
            } finally {
                System.out.println(" [x] Done");
                channel.basicAck(message.getEnvelope().getDeliveryTag(), false);  // 肯定确认
                //channel.basicNack(message.getEnvelope().getDeliveryTag(), false, false); // 否定确认
                //channel.basicReject(message.getEnvelope().getDeliveryTag(), false);      // 否定确认
            }
        };
        
        channel.basicConsume(TASK_QUEUE_NAME, false, deliverCallback, consumerTag -> {});
    }

    private static void doWork(String message) {
        for (char ch : message.toCharArray()) {
            if (ch == '.') {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        }
    }
}
